package org.lan.interview.mock;

import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.Collectors;

/**
 * @author <p><a href="mailto:1728209643@qq.com">XiaoSan</a>
 * @date 2019/11/21 2:23 PM
 */
public class Mock_002 {

    public int[][] merge(int[][] intervals) {
        if (intervals.length < 2) {
            return intervals;
        }
        intervals = Arrays.stream(intervals)
                .sorted(Comparator.comparingInt(o -> o[0]))
                .collect(Collectors.toList()).toArray(intervals);
        int p = 0;
        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i][0] - intervals[p][1] <= 0) {
                intervals[p][0] = Math.min(intervals[i][0], intervals[p][0]);
                intervals[p][1] = Math.max(intervals[i][1], intervals[p][1]);
            } else {
                p++;
                intervals[p] = intervals[i];
            }
        }

        return Arrays.copyOfRange(intervals, 0, p + 1);
    }

    public static void main(String[] args) {
        int[][] intervals = {{1, 4}, {0, 0}};
        System.out.println(Arrays.deepToString(new Mock_002().merge(intervals)));
    }

}
